package com.jake.spring.transactional.service.impl;

import com.jake.spring.transactional.domain.Employee;
import com.jake.spring.transactional.mapper.EmployeeMapper;
import com.jake.spring.transactional.oom.HeapOOM;
import com.jake.spring.transactional.oom.StackOverFlow;
import com.jake.spring.transactional.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private StackOverFlow sof;

    @Override
    public List<Employee> getAll() {
        return employeeMapper.getAll();
    }

    @Override
    @Transactional
    public int updateById(Employee employee, Integer empId) {
        return employeeMapper.updateById(employee, empId);
    }

    @Override
    @Transactional
    public int updateByIdRuntimeException(Employee employee, Integer empId) {
        int effect = employeeMapper.updateById(employee, empId);
        System.out.println(1 / 0);
        return effect;
    }

    @Override
    @Transactional(rollbackFor = IOException.class)
    public void updateByIdException(Employee employee, Integer empId) throws IOException {
        employeeMapper.updateById(employee, empId);
        throw new IOException("模拟 IO 错误");
    }

    @Override
    public Employee getById(int empId) {
        return employeeMapper.getById(empId);
    }

    @Override
    public int updateByIdWithoutTransactional(Employee employee, Integer empId) {
        return updateByIdRuntimeException(employee, empId);
    }

    @Override
    @Transactional
    public int updateByIdOOM(Employee employee, Integer empId) {
        int effect = employeeMapper.updateById(employee, empId);
        HeapOOM.mockHeapOOM();
        return effect;
    }

    @Override
    @Transactional
    public int updateByIdSOF(Employee employee, Integer empId) {
        int effect = employeeMapper.updateById(employee, empId);
        sof.stackLeak();
        return effect;
    }


}
